package com.example.demo.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {  //必须继承这个回应，这样每个接收的都会改变
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof  HashMap){
            return  body;//即以及提前执行了AjaxResult方法
        }
        if(body instanceof  String){  //原因是因为String转换类型有异常，拿ObjectMapper强转和接收
            ObjectMapper objectMapper=new ObjectMapper();
            return  objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return  AjaxResult.success(body);//即还未执行AjaxResult方法，所以立刻执行
    }
}
